<template>
    <div class="main">
        <el-container>
            <el-aside :width="'60px'">
                <div class="nav">
                    <div class="logo">
                        <img src="../../assets/avatar.gif" />
                    </div>
                    <ul>
                        <template v-for="row in store.menu" :key="row.key">
                            <li class="li" :class="{ 'is-active': menu.mainKey == row.key }"
                                @click="menuColumnSelect(row)">
                                <el-icon :size="18">
                                    <component :is="row.icon" />
                                </el-icon>
                                <span>{{ row.name }}</span>
                            </li>
                        </template>
                    </ul>
                </div>
            </el-aside>
            <el-container>
                <!-- 头部内容 -->
                <el-header class="header">
                    <div class="title">
                        艾赖可蛋糕店
                        <div class="subt" v-if="menu.data.length > 0">
                            {{ menu.mainName }}
                        </div>
                    </div>
                    <!-- 面包屑 -->
                    <div class="bread">
                        <!-- 缓存菜单栏 -->
                        <div class="tabs">
                            <Tag :value="tag.data" :active="menu.key" @emitTags="emitTags" />
                        </div>
                        <!-- <Bread :value="bread.data" /> -->
                    </div>
                    <!-- 用户信息 -->
                    <div class="info">
                        <div class="user">
                            <el-icon class="full-icon" @click="toggleFullScreen">
                                <FullScreen />
                            </el-icon>
                            <el-dropdown>
                                <span class="el-dropdown-link">
                                    <img src="../../assets/avatar.gif" alt="" />
                                    <p>您好,{{ store.adminName }}</p>
                                    <el-icon class="el-dropdown-down">
                                        <arrow-down />
                                    </el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </div>
                </el-header>
                <div class="body">
                    <template v-if="menu.data.length > 0">
                        <el-aside :width="`160px`" class="smenu">

                            <el-scrollbar>
                                <el-menu :default-active="menu.key" @select="menuSelect">
                                    <Menu :value="menu.data" />
                                </el-menu>
                            </el-scrollbar>
                        </el-aside>
                    </template>
                    <el-main>

                        <div id="view">
                            <RouterView v-slot="{ Component }">
                                <template v-if="Component">
                                    <KeepAlive ref="keep" :include="tag.includes">
                                        <component :key="$route.fullPath" :is="Component" />
                                    </KeepAlive>
                                </template>
                            </RouterView>
                        </div>
                    </el-main>
                </div>
            </el-container>
        </el-container>
    </div>
</template>
<script setup>
import Menu from './com/Menu.vue';
import Bread from './com/Bread.vue';
import Tag from './com/Tag.vue';

const { proxy } = getCurrentInstance()
const store = proxy.$pinia.state.value.store;

const flatten = computed(() => proxy.$tools.flatten(store.menu));
function menuColumnSelect(row) {
    menu.mainKey = row.key;
    row.children.length == 0 && menuSelect(row.key);
}
//菜单|选中
function menuSelect(key) {
    let item = unref(flatten).find((row) => row.key == key);
    let query = item.query ? JSON.parse(item.query) : {}
    if ([1, 2, 3].includes(Number(item.type)) && item.mode == 2) {
        return proxy.$router.push({ path: item.route, query });
    } else if (item.type == 4) {
        window.open(item.route)
    }
}

const menu = reactive({
    mainKey: '',
    mainName: '',
    key: '',
    data: []
})

const bread = reactive({
    data: []
})

const tag = reactive({
    currRoute: '',
    includes: [],
    data: []
})

//菜单|监听分栏
watch(
    () => menu.mainKey,
    (key) => {
        let find = unref(flatten).find((row) => row.key == key);
        menu.mainName = find.name;
        menu.data = find.children;
    }
);
//路由监听
watch(
    () => proxy.$router.currentRoute.value,
    (route) => routeHandle(route)
);
//路由处理
function routeHandle(route) {
    //兼容处理
    if (route.name == 'layout') {
        proxy.$router.push({ path: '/home' });
    } else {
        //标签处理
        let key = route.name;
        let find = unref(flatten).find((row) => row.key == key);
        if (find.parent > 0) {
            // 二级
            let upper1 = unref(flatten).find((row) => row.id == find.parent);
            menu.mainKey = upper1.key;
            bread.data = [upper1, find]
            if (upper1.parent > 0) {
                // 三级
                let upper2 = unref(flatten).find((row) => row.id == upper1.parent);
                menu.mainKey = upper2.key;
                bread.data = [upper1, upper2, find]
            }
        } else {
            menu.mainKey = find.key;
            bread.data = [find]
        }
        menu.key = find.key;
        if (find && find.key) {
            setTag(route)
        }

        let routeNext = localStorage.getItem('route-next');
        if (routeNext) {
            let next = JSON.parse(routeNext);
            proxy.$router.push({ path: next.path, query: next.query });
            localStorage.removeItem('route-next');
        }
    }
}

// 标签栏处理
function setTag(item) {
    let i = tag.includes.indexOf(item.name)
    if (i < 0) {
        tag.includes.push(item.name)
        tag.data.push(item)
    } else {
        tag.includes[i] = item.name
        tag.data[i] = item
    }
}

// 编辑标签
function emitTags(item, type) {

    if (type == 'click') {
        return proxy.$router.push({ path: item.path, query: item.query });
    } else {
        let i = tag.includes.indexOf(item.name)
        tag.includes.splice(i, 1)
        tag.data.splice(i, 1)
        // 当前只有一个标签，并且删除
        if (item.name == menu.key) {
            if (tag.data.length == 0) {
                return proxy.$router.push({ path: '/home' });
            }
        }
        if (tag.data.length > 0) {
            let newItem = {}
            if (type !== 'back') {
                newItem = tag.data[tag.data.length - 1]
                return proxy.$router.push({ path: newItem.path, query: newItem.query });
            }
        }
    }

}

onMounted(() => {
    getMenu()
})
async function getMenu() {
    let res = await proxy.$post("adminMenu", {}, false, false)
    if (res.code === 0) {
        store.menu = res.data.list || []
        //路由处理
        if (proxy.$route.name == 'layout') {
            routeHandle(proxy.$route);
        } else if (proxy.$route.name == 'home') {
            routeHandle(proxy.$route);
        } else {
            let next = proxy.$route;
            localStorage.setItem('route-next', JSON.stringify({ path: next.path, query: next.query }));
            proxy.$router.push({ path: '/home' });
        }
    }
}

const isFull = ref(false)
const toggleFullScreen = () => {
    isFull.value = !isFull.value
    if (!isFull.value) {
        exitfull()
    } else {
        full()
    }
}
const full = () => {
    const elem = document.documentElement
    if (elem.requestFullscreen) {
        elem.requestFullscreen()
    } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen()
    } else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen()
    } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen()
    }
}
const exitfull = () => {
    let de = document
    if (de.exitFullscreen) {
        de.exitFullscreen()
    } else if (de.mozCancelFullScreen) {
        de.mozCancelFullScreen()
    } else if (de.webkitCancelFullScreen) {
        de.webkitCancelFullScreen()
    }
}

async function logout() {
    let res = await proxy.$post("adminLogout", {}, false, false)
    if (res.code === 0) {
        localStorage.removeItem('token')
        proxy.$router.push({ path: '/' });
    }

}


// 监听跳转页面数据
function tabSwitch(key, query = null) {
    let item = unref(flatten).find((row) => row.key == key);
    if (item) {
        query == null && (query = {})
        proxy.$router.push({ path: item.route, query });
    } else {
        console.warn('[ERROR] 未匹配到菜单：' + key);
    }
}

proxy.$bus.on('tabSwitch', (parm) => {
    let key = typeof parm == 'object' ? parm.key : parm;
    let query = typeof parm == 'object' ? parm.query : null;
    tabSwitch(key, query);
});


// 监听返回
proxy.$bus.on('back', () => {
    emitTags(proxy.$route, 'back')
    proxy.$router.go(-1)
});

onUnmounted(() => {
    proxy.$bus.off('back')
});
</script>
<style scoped lang="scss">
.main {
    width: 100%;
    height: 100%;
    background-color: #f3f9ff;

    .el-container {
        height: 100%;
    }
}

.el-aside {
    display: flex;
    height: 100%;
    overflow: hidden;
    transition: all 0.3s, height 0s;

    .nav {
        width: 60px;
        height: 100%;
        background: #000;
        transition: all 0.3s;
        overflow-x: hidden;
        overflow-y: auto;
        -ms-overflow-style: none;
        /* 禁用 IE 浏览器的默认滚动条样式 */
        scrollbar-width: none;

        /* 隐藏 Firefox 的滚动条 */
        .logo {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
            cursor: pointer;

            img {
                width: 32px;
                color: #fff;
                border-radius: 50%;
            }
        }

        li {
            width: 60px;
            height: 54px;
            margin-bottom: 6px;
            display: flex;
            flex-flow: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #fff;
            transition: all 0.3s;

            &:hover {
                color: #409EFF;
            }

            &.is-active {
                color: #409EFF;
            }

            span {
                font-size: 13px;
                margin-top: 2px;
            }
        }
    }
}

.el-menu {
    border: none;

}

.header {
    height: 50px;
    background-color: #fff;
    display: flex;
    padding: 0;
    border-bottom: 1px solid #ebeef5;

    .title {
        width: 160px;
        line-height: 50px;
        font-size: 15px;
        font-weight: bold;
        text-align: center;
        position: relative;

        .subt {
            width: auto;
            height: 20px;
            font-size: 12px;
            // background-color: #fff;
            text-align: center;
            position: absolute;
            bottom: 5px;
            z-index: 3;
            left: 50%;
            transform: translateX(-50%);
            font-weight: normal;
        }

    }

    .bread {
        flex: 1;
        display: flex;
        align-items: center;
    }

    .info {
        width: 200px;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .user {
            margin: 0 10px;
            display: flex;
            align-items: center;

            .el-dropdown-link {
                display: flex;
                align-items: center;
                border: none;
            }

            img {
                width: 36px;
                height: 36px;
                margin-left: 4px;
                border-radius: 50%;
            }

            .el-dropdown-down {
                position: relative;
                top: 2px;
            }

            .el-dropdown:hover,
            .el-dropdown-link:hover {
                border: none;
            }
        }

        .full-icon {
            margin-right: 10px;
            font-size: 22px;
        }
    }
}

.body {

    height: calc(100% - 50px);
    display: flex;

    .smenu {
        height: 100%;
        padding-top: 20px;

        ::v-deep .el-menu-item {
            padding: 0 5px;
            height: 42px;
        }

        background-color: #fff;

    }

    .el-scrollbar {
        width: 160px;
    }
}

.el-main {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;

    #view {
        padding: 10px;
        flex: 1;
        overflow: hidden;
    }
}
</style>
